package com.springmvc.web.majiang.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.springmvc.web.majiang.entity.User;
import com.springmvc.web.majiang.service.IUserService;

/**
 * 
 * @ClassName: LoginController 
 * @author wangruchao
 * @date 2017年12月11日 上午11:52:40
 */
@Controller
@RequestMapping
public class LoginController {

	@Autowired
	IUserService userService;

	@RequestMapping("/tologin")
	public String index(@RequestParam(value = "toPath",
									  defaultValue = "",
									  required = false) String toPath,
			Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
		model.addAttribute("toPath", toPath);
		return "login";
	}

	@RequestMapping("/login")
	public String index(@RequestParam(value = "toPath") String toPath, @RequestParam("username") String username,
			@RequestParam("password") String password, Model model, HttpServletRequest request,
			HttpServletResponse response) {
		Wrapper<User> wrapper = new EntityWrapper<User>();
		wrapper.eq("username", username);
		User user = userService.selectOne(wrapper);
		if (user == null) {
			System.err.println("用户不存在");
		}
		if (!StringUtils.equalsIgnoreCase(password, user.getPassword())) {
			System.err.println("密码错误");
		}
		HttpSession session = request.getSession();
		session.setAttribute("userInfo", user);
		if (StringUtils.isNotBlank(toPath)) {
			return "redirect:" + toPath;
		}
		model.addAttribute("userid", user.getId());
		return "redirect:/room";
	}

}
